package com.example.demo_text;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import user.User;

import java.io.IOException;
import java.sql.Date;

@WebServlet("/PublishAssignmentServlet")
public class PublishAssignmentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        try {
            User user = (User) request.getSession().getAttribute("user");
            if (user == null || user.getUserType().equals("student")) {
                request.setAttribute("assignmentError", "权限不足：仅教师或管理员可发布作业");
                request.getRequestDispatcher("/class_space.jsp").forward(request, response);
                return;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("error.jsp?message=" + e.getMessage());
            return;
        }
        try {
            // Get parameters from the request
            String courseIdStr = request.getParameter("course_id");
            String assignmentTitle = request.getParameter("assignment_title");
            String assignmentContent = request.getParameter("assignment_content");
            String dueDateStr = request.getParameter("due_date");
            String maxScoreStr = request.getParameter("max_score");
            
            // Convert parameters to appropriate types
            int courseId = Integer.parseInt(courseIdStr);
            int maxScore = Integer.parseInt(maxScoreStr);
            
            // Convert string date to SQL type
            Date dueDate = Date.valueOf(dueDateStr);
            
            // By default, set assignments as active
            boolean active = true;
            
            // Add assignment to database
            boolean success = AssignmentDAO.addAssignment(courseId, assignmentTitle, 
                                                        assignmentContent, dueDate, 
                                                        maxScore, active);
            
            if (success) {
                // Redirect back to class_space.jsp with the assignments tab active
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&tab=assignments");
            } else {
                // If there was an error, redirect with an error parameter
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&tab=assignments&error=Failed to create assignment");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            // If an error occurred, redirect to an error page
            response.sendRedirect("error.jsp?message=" + e.getMessage());
        }
    }
} 